/*
Copyright (c) 2012, 2013 Regents of the University of California
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions 
are met:

 - Redistributions of source code must retain the above copyright
   notice, this list of conditions and the following disclaimer.
 - Redistributions in binary form must reproduce the above copyright
   notice, this list of conditions and the following disclaimer in the
   documentation and/or other materials provided with the
   distribution.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS 
FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL 
THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, 
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR 
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, 
STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED 
OF THE POSSIBILITY OF SUCH DAMAGE.
*/

var smaputil = smaputil || {};

/*
smaputil.loadData = function(final_dict, t_dict, start, end, resample_s) { 
    var defer = $.Deferred()
    var requests = []
    var diffData = {}
    var hist_data = []
    for (var i in final_dict) {
    	diffData[t_dict[i]] = [];
        var query = 'apply diff(axis=1) < paste < window(first, field=\'second\', width=' + String(resample_s) + ') to data in (' + String(start) + ',' + String(end) + ') where uuid = \"' + i + '\" or uuid = \"' + final_dict[i] + '\"';
        console.log(query)
        //console.log([i, t_dict, final_dict[i]])
        var opts = {
        	async: false,
        	type : 'POST',
			url : "/backend/api/query",
			data : query,
            success : function(resp) {
                //console.log(resp)
                var result = eval(resp);
                console.log(i)
                if (typeof result[0] != 'undefined'){
	                d = result[0].Readings;
	                for (var j=0; j<d.length; j++){
	                	hist_data.push(d[j][1]);
	                	diffData[t_dict[i]].push(d[j][1]);	
	                }
                }
                else {console.log('missing data')}
            },
        };
        requests.push($.ajax(opts));
    };
        $.when.apply($, requests).then(function(){
            defer.resolve([hist_data, diffData]);
        });
    return defer.promise();
}

smaputil.loadData = function(streamids, start, end) {
    var defer = $.Deferred()
    var requests = []
    var resultData = {}
    streamids.forEach(function(element) {
        var query = "/backend/api/data/uuid/" + element + "?starttime=" + escape(start) + "&endtime=" + escape(end);
        var opts = {
            url : query,
            success : function(resp) {
                var result = eval(resp);
                if (typeof result[0] != 'undefined'){
                        d = result[0].Readings;
                        resultData[element] = d;        
                }
                else {console.log('missing data')}
            },
        };
        requests.push($.ajax(opts));
    });
        $.when.apply($, requests).then(function(){
            defer.resolve(resultData);
        });
    return defer.promise();
}
*/

//loadPaths, like loadUuids returns a path, uuid object
smaputil.loadPaths = function(uuids) {
	var defer = $.Deferred();
	var requests = [];
	var paths = {};
	uuids.forEach(function(element) {
		query = 'select distinct Path where uuid = "' + element + '"';
		//console.log(query);
		requests.push($.ajax({
			type : 'POST',
			url : "/backend/api/query",
			data : query,
			success : function(resp) {
				var result = eval(resp);
                d = result[0];
                paths[d] = element;
			}
		}));
	});
	$.when.apply($, requests).then(function(){
		defer.resolve(paths);
		}
	);
	return defer.promise();
}

smaputil.loadUuids = function(paths) {
    var defer = $.Deferred();
    var requests = [];
    var uuids = {};
    paths.forEach(function(element) {
        query = 'select distinct uuid where Path like "' + element + '"';
        requests.push($.ajax({
            type : 'POST',
            url : "/backend/api/query",
            data : query,
            success : function(resp) {
                uuid = eval(resp);
                if (uuid.length > 1){
                    uuids = uuid
                }else{
                    uuids[element] = uuid[0]
                }
            }
        }));
    });
    $.when.apply($, requests).then(function(){
        defer.resolve(uuids);
    });
    return defer.promise();
}

smaputil.filterTime = function(d, weekday, start_h, end_h, tz) {
    if( typeof (weekday) === 'undefined')
        weekday = false;
    var result = [], t, day, hour, cond;
    d.forEach(function(element) {
	        t = new Date(element[0] + tz*3600000);
	        day = t.getUTCDay();
	        hour = t.getUTCHours();
	        //console.log(day, hour);
	        cond = hour >= start_h && hour < end_h
	        if(weekday)
	            cond = cond && (day != 0 && day != 6)
	        if(cond)
	            result.push(element);
    });
    return result;
}

Array.prototype.avg = function(){
    var items = this;
    if (items.length < 1) return 0;
    var N = items.length, s = 0, mu;
    items.forEach(function(e){
 	    if (!isNaN(e)){
 	    	s += e;
 	    }
 	    else (N = N-1)
    });
    mu = s / N;
    return mu;
} 

Array.prototype.v_subtract = function(other) {
	items = this;
	if( typeof (other) === 'undefined')
		return [];
	if(items.length != other.length)
		return [];
	if(items.length < 1)
		return [];
	result = [];
	for(var i = 0; i < items.length; i++) {
		if (!isNaN(items[i]) && !isNaN(other[i])){
			result.push(items[i] - other[i]);
		}
	};
	return result;
}

Array.prototype.std = function(){
    var items = this;
    if (items.length < 1) return 0;
    var N = items.length, s = 0, sigma;
    var mu = items.avg();
    items.forEach(function(e){
    	if (!isNaN(e)){
        	s += Math.pow(e - mu, 2)
       	}
        else N = N-1;
    });
    sigma = Math.sqrt(s / N);
    return sigma;
}

smaputil.objectValues = function(obj){
    var values = []
    if (typeof(obj) == 'object'){
	    Object.keys(obj).forEach(function(el){
	        values.push(obj[el])
	    })
	    return values
	}
}

smaputil.linterp = function(x0, y0){
    // x0: monotonically increasing array
    // y0: corresponding y-values to x0, such that dim(x0) = dim(y0)
    // returns function that interpolates ynew given xnew
    var N = x0.length
    var searchsorted = function(a, v){ 
        // a : sorted, monotonically increasing array
        // v : value to insert into array a
        // returns index i,such that a[i-1] <= v <= a[i]
        var N = a.length
        for (var k = 0; k < N; k++){
            if (v <= a[k]) return k
        }
        return N
    }
    
    return function(xnew){
	    var ind = searchsorted(x0, xnew)
	    if (ind <= 0 || ind >= N) return NaN 
	    var x_hi = x0[ind] 
	    var x_lo = x0[ind-1]
	    var y_hi = y0[ind]
	    var y_lo = y0[ind-1]
	    var slope = (y_hi - y_lo) / (x_hi - x_lo)

   		ynew = slope * (xnew - x_lo) + y_lo
    	return ynew
    }
}

smaputil.resolveKeys = function(uuid_dict, d){
    var oldpath
    Object.keys(uuid_dict).forEach(function(path){
        oldpath = uuid_dict[path] //uuid of a particular path
        d[path] = d[oldpath] //exchange path for uuid as the key in the data
        delete d[oldpath]
    })
    return d
}

smaputil.switchObject = function(uuid_dict){
    var uuid
    var d = {}
    Object.keys(uuid_dict).forEach(function(path){
        uuid = uuid_dict[path] //uuid of a particular path
        d[uuid] = path //exchange path for uuid as the key in the data
    })
    return d
}

smaputil.transpose = function(d){
    Object.keys(d).forEach(function(key){
        var times = [], vals = []
        d[key].forEach(function(element){
            times.push(element[0])
            vals.push(element[1])
        })
        d[key] = [times, vals]
    })
    return d
}

